﻿using AntdUI;
using S7SingalTool.Forms;
using S7SingalTool.Models;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZR.Model.Models.ProductionControl;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace S7SingalTool.Controls
{
    public partial class CollectDataConfigPage : BaseUserControl
    {
        public CollectDataConfigPage()
        {
            InitializeComponent();
            this.Load += CollectDataConfigPage_Load;
        }

        private void CollectDataConfigPage_Load(object sender, EventArgs e)
        {
            InitTable();
            InitFieldTable();
            InitActionTable();
            ReflushData();
            txtSearch.TextChanged += TxtSearch_TextChanged;
        }

        private void TxtSearch_TextChanged(object sender, EventArgs e)
        {
            ReflushData();
        }

        private void InitTable()
        {
            table1.EditMode = TEditMode.None;
            table1.Columns = new ColumnCollection();
            table1.Columns.Add(new Column("TableName", "表名"));
            //table1.Columns.Add(new Column("Notes", "备注"));

            table1.Bordered = true;
            table1.EnableHeaderResizing = true;
            table1.EmptyHeader = true;
            table1.Gap = 6;
            table1.VisibleHeader = false;

            table1.CellClick += Table1_CellClick;
        }

        private void InitFieldTable()
        {
            table2.EditMode = TEditMode.Click;
            table2.Columns = new ColumnCollection();

            table2.Columns.Add(new Column("Sequence", "顺序") { });
            table2.Columns.Add(new Column("Notes", "备注"));
            table2.Columns.Add(new Column("ColumnName", "列头名称"));
            table2.Columns.Add(new Column("DataId", "数据ID"));
            table2.Columns.Add(new ColumnCheck("IsPrimary", "主码"));
            table2.Columns.Add(new ColumnCheck("IsResult", "结果"));
            table2.Columns.Add(new Column("Width", "宽度"));
            table2.Columns.Add(new ColumnCheck("IsDisplay", "显示"));
            //table2.Columns.Add(new Column("LanguageKey", "翻译Key"));

            table2.Bordered = true;
            table2.EnableHeaderResizing = true;
            table2.EmptyHeader = true;
            table2.Gap = 6;
            table2.VisibleHeader = true;
            table2.CellBeginEditInputStyle += (s, e) =>
            {
                e.Input.SelectAll();
            };

            table2.CellClick += (s, e) =>
            {
                var config = e.Record as CksVirtualColumn;
                if (e.Button == MouseButtons.Right)
                    ShowRightButton(table2, config);
            };
            table2.CellClick += Table2_CellClick;
        }

        private void Table2_CellClick(object sender, TableClickEventArgs e)
        {
           var item = e.Record as CksVirtualColumn;
            if (item != null)
            {
                if(item.IsPrimary)
                {
                    var items = FieldSource.ToList().FindAll(a => a.Guid != item.Guid && a.IsPrimary);
                    foreach (var cc in items)
                    {
                        cc.IsPrimary = false;
                    }
                }

                if(item.IsResult)
                {
                    var items = FieldSource.ToList().FindAll(a => a.Guid != item.Guid && a.IsResult);
                    foreach (var cc in items)
                    {
                        cc.IsResult = false;
                    }
                }

               
            }
           // MessageInfo($"{item.IsPrimary}");
        }



        // 

        private void InitActionTable()
        {
            table3.EditMode = TEditMode.Click;
            table3.Columns = new ColumnCollection();

            table3.Columns.Add(new Column("PlcId", "PlcId") { });
            table3.Columns.Add(new Column("ActionId", "动作"));
            table3.Columns.Add(new Column("ActionKey", "动作Key"));
            table3.Columns.Add(new Column("ReadDB", "ReadDB"));
            table3.Columns.Add(new Column("WriteDB", "WriteDB"));


            table3.Bordered = true;
            table3.EnableHeaderResizing = true;
            table3.EmptyHeader = true;
            table3.Gap = 6;
            table3.VisibleHeader = true;
            table3.CellBeginEditInputStyle += (s, e) =>
            {
                e.Input.SelectAll();
            };

            table3.CellClick += (s, e) =>
            {
                var config = e.Record as CksPlcActions;
                if (e.Button == MouseButtons.Right)
                    ShowRightButton(table3, config);
            };

        }




        private void Table1_CellClick(object sender, TableClickEventArgs e)
        {
            var config = e.Record as CksVirtualTable;
            Context = config;
            if (e.Button == MouseButtons.Left)
                LoadCheckData(Context);
            else if (e.Button == MouseButtons.Right)
                ShowRightButton(table1, config);
        }



        private void ShowRightButton(Table table, object data)
        {
            List<IContextMenuStripItem> menus = new List<IContextMenuStripItem>();
            menus.Add(new ContextMenuStripItem("删除")
            {
                ID = "delete"
                //IconSvg = "CloseOutlined"
            });

            AntdUI.ContextMenuStrip.open(table, OnClickRightMenu(data), menus.ToArray());
        }

        private Action<ContextMenuStripItem> OnClickRightMenu(object data)
        {
            var db = SqlSugarHelper.MesDB;
            Action<ContextMenuStripItem> action = (menu) =>
            {
                switch (menu.ID)
                {

                    case "delete":

                        var result = MessageBoxWarn("删除警告", "确认要删除吗");
                        if (result != DialogResult.OK)
                            return;
                        if (data is CksVirtualTable)
                        {
                            var tableId = (data as CksVirtualTable).Id;
                            //删除采集的数据
                            db.Deleteable<CksCollectedDetails>().Where(a => a.TableId == tableId).ExecuteCommand();
                            db.Deleteable<CksCollected>().Where(a => a.TableId == tableId).ExecuteCommand();
                            //同时删除动作和结构
                            db.Deleteable<CksVirtualColumn>().Where(a => a.TableId == tableId).ExecuteCommand();
                            db.Deleteable<CksPlcActions>().Where(a =>a.ActionType == 1 && a.BusinessId == tableId).ExecuteCommand();
                            db.Deleteable<CksVirtualTable>(data).ExecuteCommand();
                            

                            Source.Remove(data as CksVirtualTable);
                        }
                        if (data is CksVirtualColumn)
                        {
                            db.Deleteable<CksVirtualColumn>(data).ExecuteCommand();
                            FieldSource.Remove(data as CksVirtualColumn);
                        }
                        if (data is CksPlcActions)
                        {
                            db.Deleteable<CksPlcActions>(data).ExecuteCommand();
                            ActionsSource.Remove(data as CksPlcActions);
                        }
                        MessageInfo("OK");
                        break;
                    default:
                        break;
                }


            };
            return action;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            var res = new VirtualTableForm().ShowDialog();
            if (res == DialogResult.OK)
            {
                ReflushData();
            }
        }

        BindingList<CksVirtualTable> Source = new BindingList<CksVirtualTable>();
        BindingList<CksVirtualColumn> FieldSource = new BindingList<CksVirtualColumn>();
        BindingList<CksPlcActions> ActionsSource = new BindingList<CksPlcActions>();
        CksVirtualTable Context = null;
        /// <summary>
        /// 刷新数据
        /// </summary>
        public void ReflushData()
        {
            string search = txtSearch.Text;
            Source.Clear();
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksVirtualTable>()
                   .WhereIF(!search.IsNullOrEmpty(), (a) => a.TableName.Contains(search))
                   .OrderBy(a=>a.Sequence)
                   .ToList();
            foreach (var item in lst)
            {
                Source.Add(item);
            }
            this.table1.Binding(Source);
            if (Source.Count > 0)
            {
                if (table1.SelectedIndex < 1)
                {
                    table1.SelectedIndex = 1;
                    Context = Source[0];
                    LoadCheckData(Context);
                }
                else
                {
                    Context = Source[table1.SelectedIndex - 1];
                    LoadCheckData(Context);
                }
            }
            else
            {
                //没有数据清理另外两个表
                LoadCheckData(null);
            }

        }

        private void LoadCheckData(CksVirtualTable context)
        {
            FieldSource.Clear();
            ActionsSource.Clear();
            if (context == null)
                return;
            //加载虚拟表字段
            LoadColumnData(context.Id);
            //加载绑定动作
            LoadPlcActions(context.Id);
        }

        private void LoadColumnData(int tableId)
        {
            FieldSource.Clear();
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksVirtualColumn>().Where(a => a.TableId == tableId).OrderBy(a => a.Sequence).ToList();
            foreach (var item in lst)
            {
                FieldSource.Add(item);
            }
            this.table2.Binding(FieldSource);
        }

        private void LoadPlcActions(int tableId)
        {
            ActionsSource.Clear();
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<CksPlcActions>().Where(a => a.ActionType == 1 && a.BusinessId == tableId).OrderBy(a => a.Id).ToList();
            foreach (var item in lst)
            {
                ActionsSource.Add(item);
            }
            this.table3.Binding(ActionsSource);
        }

        private void btnOpenEdit_Click(object sender, EventArgs e)
        {
            if (Context == null)
                return;
            var res = new VirtualTableForm(Context).ShowDialog();
            if (res == DialogResult.OK)
            {
                ReflushData();
            }
        }

        private void btnAddField_Click(object sender, EventArgs e)
        {
            if (Context == null)
                return;
            FieldSource.Add(new CksVirtualColumn() { IsDisplay = true,Width = 120 });
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (Context == null) return;
            if (ActionsSource.Count == 0)
            {
                MessageError("请先配置动作");
                return;
            }
            var result = MessageBoxWarn("警告", "从点位配置提取数据,是否继续");
            if (result == DialogResult.OK)
            {
                var act = ActionsSource[0];
                var db = SqlSugarHelper.MesDB;
                var items = db.Queryable<CksPlcDataPosition>()
                    .Where(a => a.PlcId == act.PlcId && a.BlockDb == act.ReadDB && a.LinkActionId == act.ActionId)
                    .OrderBy(a => a.DataId).ToList();

                foreach (var item in items)
                {
                    var one = FieldSource.ToList().Find(a => a.DataId == item.DataId);
                    if (one == null)
                        FieldSource.Add(new CksVirtualColumn() { Notes = item.Description, DataId = item.DataId,IsDisplay=true,Width=120 });
                }
            }
        }

        private void btnSaveField_Click(object sender, EventArgs e)
        {
            if (Context == null) return;
            var items = FieldSource.ToList().OrderBy(a => a.Sequence).ToList();
            if(items.Find(a=>a.IsPrimary) == null)
            {
                MessageError("必须设置主码");
                return;
            }

            var db = SqlSugarHelper.MesDB;
            foreach (var item in items)
            {
                item.TableId = Context.Id;
                if (item.Id == 0)
                    db.Insertable(item).ExecuteCommand();
                else
                {
                    db.Updateable(item).ExecuteCommand();
                }
            }
            LoadColumnData(Context.Id);
            MessageInfo("OK");
        }

        private void btnLoadData_Click(object sender, EventArgs e)
        {
            if (Context == null) return;
            LoadColumnData(Context.Id);
        }

        private void btnAddAction_Click(object sender, EventArgs e)
        {
            ActionsSource.Add(new CksPlcActions() { });
        }

        private void btnSaveActions_Click(object sender, EventArgs e)
        {
            if (Context == null) return;
            var items = ActionsSource.ToList().OrderBy(a => a.ActionId).ToList();
            var db = SqlSugarHelper.MesDB;
            try
            {
                foreach (var item in items)
                {
                    item.BusinessId = Context.Id;
                    item.ActionType = 1;
                    item.Name = "数据采集";

                    if (item.Id == 0)
                        db.Insertable(item).ExecuteCommand();
                    else
                        db.Updateable(item).ExecuteCommand();
                }
                LoadPlcActions(Context.Id);
                MessageInfo("OK");
            }
            catch (Exception ex)
            {
                MessageError("保存失败，可能是动作编号重复");
            }
        }

        private void btnReflush_Click(object sender, EventArgs e)
        {
            ReflushData();
        }
    }
}
